/**
 * 单个实例中, 创建两个方法, 使用同一个锁对象
 */
public class SynchronizedExample6 {

    static int count = 0;

    // 定义一个锁对象
    Object locker = new Object();

    public void increment1 () {
        synchronized (locker) {
            count++;
        }
    }

    public void increment2 () {
        synchronized (locker) {
            count++;
        }
    }

    public int getCount() {
        return count;
    }

    public static void main(String[] args) {

        SynchronizedExample6 example = new SynchronizedExample6();

        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                example.increment1();
            }
        });
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                example.increment2();
            }
        });

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(example.getCount());
    }
}

// 20000